<template>
	<view class="container">
		<view class="uni-list">
			<!-- <view class="uni-list-cell uni-list-cell-pd" @click="saveAvatar">
				<view>头像</view>f
				<view class="uni-list-cell-db">
					<image :src="userInfo.headImgUrl" class="pic"></image>
				</view>
				<view class="uni-navigate-right"></view>
			</view> -->
			<view class="uni-list-cell uni-list-cell-pd">
				<view>头像</view>
				<view class="uni-navigate-right">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="avatar" :src="userInfo.headImgUrl"></image>
					</button>
				</view>
			</view>
			<!-- <view class="uni-list-cell uni-list-cell-pd" @click="showUserName = true">
				<view>联系人</view>
				<view class="uni-list-cell-db">{{userInfo.userName || ''}}</view>
				<view class="uni-navigate-right"></view>
			</view> -->
			<view class="uni-list-cell uni-list-cell-pd" @click="showUserName = true">
				<view>联系人</view>
				<view class="uni-list-cell-db">{{userInfo.userName || ''}}</view>
				<view class="uni-navigate-right"></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd" @click="showContactPhone = true">
				<view>手机</view>
				<view class="uni-list-cell-db">{{userInfo.contactPhone || ''}}</view>
				<view class="uni-navigate-right"></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd" v-if="userInfo.expiryDate">
				<view>我的会员</view>
				<view class="uni-list-cell-db">{{formatDate(userInfo.expiryDate) || ''}}</view>
				<view class="uni-navigate-right"></view>
			</view>
			<block v-if="userType == 'STORE'">
				<view class="uni-list-cell uni-list-cell-pd" @click="showStoreName = true">
					<view>所属门店</view>
					<view class="uni-list-cell-db">{{userInfo.storeName || ''}}</view>
					<view class="uni-navigate-right"></view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view>门店地址</view>
					<view class="uni-list-cell-db" @click="show = !show">
						<u-picker :show="show" ref="uPicker" :loading="loading" :columns="columns" keyName="areaName"
							@change="changeHandler" itemHeight="88" @confirm="confirm"
							@cancel="show = false"></u-picker>
						<view class="uni-navigate-right" type="text" style="padding: 15rpx 0;">{{citystr}}</view>
					</view>
					<view class="uni-navigate-right"></view>
				</view>
				<view v-if="!bgUserType" class="uni-list-cell uni-list-cell-pd" @click="applyStore('STORE')">
					<view>我是品牌批发商</view>
					<view class="uni-list-cell-db">
					</view>
					<view class="uni-navigate-right"></view>
				</view>
			</block>
			<block v-if="userType == 'SALE'">
				<view class="uni-list-cell uni-list-cell-pd" @click="showStoreName = true">
					<view>公司名称</view>
					<view class="uni-list-cell-db">{{userInfo.storeName}}</view>
					<view class="uni-navigate-right"></view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view>公司地址</view>
					<view class="uni-list-cell-db" @click="show = !show">
						<u-picker :show="show" ref="uPicker" :loading="loading" :columns="columns" keyName="areaName"
							@change="changeHandler" itemHeight="88" @confirm="confirm"
							@cancel="show = false"></u-picker>
						<view class="uni-navigate-right" type="text" style="padding: 15rpx 0;">{{citystr}}</view>
					</view>
					<view class="uni-navigate-right"></view>
				</view>
				<!-- 				<view class="uni-list-cell uni-list-cell-pd">
					<view>主营品牌</view>
					<view class="uni-list-cell-db">{{userInfo.categoryList}}</view>
					<view class="uni-navigate-right"></view>
				</view> -->
				<!-- <view class="uni-list-cell uni-list-cell-pd" @click="applyStore('SALE')">
					<view>申请批发商</view>
					<view class="uni-list-cell-db">
					</view>
					<view class="uni-navigate-right"></view>
				</view> -->
			</block>
			<view class="uni-list-cell uni-list-cell-pd" v-if="userType == 'STORE'||userType == 'SALE'" @click="goRole">
				<view>身份选择</view>
				<view class="uni-list-cell-db">
					{{userType == 'CAR' ? '车主' : (userType == 'STORE' ? '门店' : (userType == 'SALE' ? '批发商' : ''))}}
				</view>
				<view class="uni-navigate-right"></view>
			</view>
			<view class="flex-row row-between-wrapper pd-30">
				<view class="pic" @click="updatePhysical">
					<image :src="userInfo.physicalStoreUrl"></image>
				</view>
			</view>
			<!-- v-if="!isStore||userType=='CAR'" -->
			<!-- 	<view class="uni-list-cell uni-list-cell-pd"  @click="toStore()">
				<view>申请门店</view>
				<view class="uni-navigate-right"></view>
			</view> -->
			<view class="flex-row row-between-wrapper pd-30">
				<view class="pic" @click="updateAuthCert">
					<image :src="userInfo.authCertUrl"></image>
				</view>
			</view>
		</view>
		<view class="footer">
			<u-button type="primary" color="#06A972" text="退出登录" @click="logout"></u-button>
			<!-- <button type="primary" @>退出登录</button> -->
		</view>
		<u-modal :show="showUserName" title="修改姓名" @confirm="updateUserName" showCancelButton
			@cancel="showUserName = false">
			<u--input placeholder="请输入姓名" border="surround" v-model="userName" type="nickname"></u--input>
		</u-modal>
		<u-modal :show="showContactPhone" title="修改手机号" @confirm="updatePhone" showCancelButton
			@cancel="showContactPhone = false">
			<u--input placeholder="请输入手机号" border="surround" v-model="contactPhone" type="text"></u--input>
		</u-modal>
		<u-modal :show="showStoreName" title="修改所属门店" @confirm="updateStoreName" showCancelButton
			@cancel="showStoreName = false">
			<u--input placeholder="请输入所属门店" border="surround" v-model="storeName" type="text"></u--input>
		</u-modal>
		<u-modal :show="showAddress" title="详细地址" @confirm="updateStoreAddress" showCancelButton
			@cancel="showAddress = false">
			<u--input placeholder="请输入详细地址" border="surround" v-model="address" type="text"></u--input>
		</u-modal>

	</view>
</template>


<script>
	var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
	var qqmapsdk;
	import {
		toStore
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	import {
		getUserInfo,
		updateUserInfo,
	} from "@/api/user.js";
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	export default {
		data() {
			return {
				avatarUrl: '',
				userInfo: {},
				bgUserType: 0,
				showUserName: false,
				userName: '',
				contactPhone: '',
				showContactPhone: false,
				showStoreName: false,
				storeName: '',
				// 地址
				showAddress: false,
				show: false,
				loading: false,
				columns: [
					[],
					[],
					[]
				],
				provinceList: [],
				cityList: [],
				areaList: [],
				defaultProvince: 110000, //北京市
				defaultCity: 110100, //北京市
				citystr: '',
				provinceCode: 0,
				cityCode: 0,
				districtCode: 0,
				address: ''
			}

		},

		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				userType: 'userType',
				isStore: 'isStore',
			})
		},

		onLoad() {
			qqmapsdk = new QQMapWX({
				key: 'TNABZ-LWUCW-VT2RC-3XZY6-2N5LT-NIFGJ'
			});
			this.getUserInfo();
			/**
			 * 获取默认地址
			 */
			this.defaultAddress();
		},

		onShow() {
			let that = this;
			console.log("身份组成：userType=" + this.userType)
		},

		methods: {
			formatDate(date) {
				if (!date) return "";
				const expiryDate = new Date(date);
				const currentDate = new Date(); // 获取当前时间
				
				// 将日期转换为 UTC+8
				expiryDate.setHours(expiryDate.getHours() + 8);
				currentDate.setHours(currentDate.getHours() + 8);
				
				if (expiryDate < currentDate) {
				    return expiryDate.toISOString().split('T')[0] + " 已过期";
				} else {
				    return expiryDate.toISOString().split('T')[0] + " 到期";
				}
			},
			onChooseAvatar(e) {
				let that = this;
				const {
					avatarUrl
				} = e.detail
				this.userInfo.headImgUrl = avatarUrl
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/' + 'user/updateHeadImage',
					filePath: avatarUrl,
					name: 'headImageFiles',
					formData: {
						'userInfoId': that.uid
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
					},
					success: function(res) {
						uni.hideLoading();
						let data = res.data ? JSON.parse(res.data) : {};
						console.log(data);
					},
					fail: function(res) {
						uni.hideLoading();
						that.Tips({
							title: '上传图片失败'
						});
					}
				})
			},
			toStore() {
				toStore();
			},
			/**
			 * 选择地址
			 * @param {Object} e
			 */
			changeHandler(e) {
				let that = this;
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = that.$refs.uPicker,
					value
				} = e
				if (columnIndex === 0) {
					that.loading = true
					// 获取市
					that.getAddress(value[columnIndex].areaId).then(res => {
						picker.setColumnValues(1, res)

						// 获取区
						that.getAddress(res[columnIndex].areaId).then(res => {
							picker.setColumnValues(2, res)
							that.loading = false
						})
					})
				}
				if (columnIndex === 1) {
					// 获取区
					that.getAddress(value[columnIndex].areaId).then(res => {
						picker.setColumnValues(2, res)
						that.loading = false
					})
				}
			},
			/**
			 * 获取用户信息
			 */
			getUserInfo() {
				let that = this;
				getUserInfo({
					userInfoId: that.uid
				}).then(res => {
					console.log(res.value);
					that.userInfo = res.value;
					that.bgUserType = parseInt(res.value.bgUserType);
					that.citystr = res.value.province + ' ' + res.value.city + ' ' + res.value.area + ' ' + res
						.value.address
					console.log(that.bgUserType);
					that.$store.commit("UPDATE_USERINFO", res.value);
				})
			},

			/**
			 * 选择身份
			 */
			goRole() {
				this.$util.Tips('/pages/users/user_role/index');
			},

			/**
			 * 申请门店
			 */
			applyStore(type) {
				if (type == 'CAR') {
					this.$util.Tips('/pages/users/applyStore/index')
				} else {
					this.$util.Tips('/pages/users/apply_agent/index')
				}
			},

			/**
			 * 更换头像
			 */
			saveAvatar() {
				let that = this
				that.$util.uploadImageOne({
					url: 'user/updateHeadImage',
					name: 'headImageFiles',
					uid: that.uid
				}, function(res) {
					if (res.resultCode == 1) {
						that.getUserInfo();
						that.$util.Tips({
							title: '更换成功',
						}, {
							tab: 3
						})
					}
				});
			},

			/**
			 * 更新名字
			 */
			updateUserName() {
				let that = this;
				if (!that.userName) {
					return that.$util.Tips({
						title: '请输入名称'
					})
				}
				updateUserInfo({
					userInfoId: that.uid,
					userName: that.userName
				}).then(res => {
					that.showUserName = false;
					that.getUserInfo();
					that.userName = '';
					that.$util.Tips({
						title: '修改成功'
					})
				}).catch(err => {
					that.$util.Tips({
						title: '修改失败'
					})
				})
			},

			/**
			 * 更新手机号
			 */
			updatePhone() {
				let that = this;
				if (!that.contactPhone) {
					return that.$util.Tips({
						title: '请输入手机号'
					})
				}
				updateUserInfo({
					userInfoId: that.uid,
					contactPhone: that.contactPhone
				}).then(res => {
					that.showContactPhone = false;
					that.getUserInfo();
					that.contactPhone = '';
					that.$util.Tips({
						title: '修改成功'
					})
				}).catch(err => {
					that.$util.Tips({
						title: '修改失败'
					})
				})
			},

			/**
			 * 更新所属门店
			 */
			updateStoreName() {
				let that = this;
				if (!that.storeName) {
					return that.$util.Tips({
						title: '请输入所属门店'
					})
				}
				updateUserInfo({
					userInfoId: that.uid,
					storeName: that.storeName
				}).then(res => {
					that.showStoreName = false;
					that.getUserInfo();
					that.storeName = '';
					that.$util.Tips({
						title: '修改成功'
					})
				}).catch(err => {
					that.$util.Tips({
						title: '修改失败'
					})
				})
			},

			/**
			 * 更新门店位置
			 */
			updateStoreAddress() {
				let that = this;
				if (!that.provinceCode) {
					return that.$util.Tips({
						title: '请选择地址'
					})
				}
				if (!that.address) {
					return that.$util.Tips({
						title: '请输入详细地址'
					})
				}

				qqmapsdk.geocoder({
					address: this.citystr + this.address, // 地址信息
					success(res) {
						updateUserInfo({
							userInfoId: that.uid,
							provinceCode: that.provinceCode,
							cityCode: that.cityCode,
							districtCode: that.districtCode,
							address: that.address,
							latitude: res.result.location.lat,
							longitude: res.result.location.lng,
						}).then(res => {
							that.showAddress = false;
							that.getUserInfo();
							that.address = '';
							that.provinceCode = 0;
							that.cityCode = 0;
							that.districtCode = 0;
							that.$util.Tips({
								title: '修改成功'
							})
						}).catch(err => {
							that.$util.Tips({
								title: '修改失败'
							})
						})
					},
					fail(err) {
						// 失败回调
						console.error(err);
					}
				});
			},

			/**
			 * 获取默认地址
			 */
			defaultAddress() {
				let that = this;
				// 获取所有省
				that.getAddress(1).then(res => {
					that.provinceList = res

					// 获取默认市
					that.getAddress(that.defaultProvince).then(res => {
						that.cityList = res

						// 获取默认区
						that.getAddress(that.defaultCity).then(res => {
							that.areaList = res
							that.columns = [
								[...that.provinceList],
								[...that.cityList],
								[...that.areaList]
							];
						});
					});
				});
			},

			/**
			 * 地址确认
			 * @param {Object} e
			 */
			confirm(e) {
				console.log('confirm', e)
				let that = this;
				that.provinceCode = e.value[0].areaId;
				that.cityCode = e.value[1].areaId;
				that.districtCode = e.value[2].areaId;
				that.citystr = e.value[0].areaName + '/' + e.value[1].areaName + '/' + e.value[2].areaName;
				this.showAddress = true;
				this.show = false;
			},

			getAddress(id) {
				return new Promise((resolve, reject) => {
					let that = this;
					that.$request.get('area/getAreaList', {
						parentId: id
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						that.$util.Tips({
							title: err.msg
						});
					})
				});
			},

			/**
			 * 更新店铺资料
			 */
			updatePhysical() {
				let that = this
				that.$util.uploadImageOne({
					url: 'user/updateUserInfo',
					name: 'storeImageFile',
					uid: that.uid
				}, function(res) {
					if (res.resultCode == 1) {
						that.getUserInfo();
						that.$util.Tips({
							title: '更换成功',
						}, {
							tab: 3
						})
					}
				});
			},



			/**
			 * 退出登录
			 */
			logout() {
				let that = this;
				uni.showModal({
					content: '确定退出登录吗？',
					success(res) {
						if (res.confirm) {
							that.$store.commit("LOGOUT");
							uni.reLaunch({
								url: '/pages/user/index'
							})
							// that.$request.get('user/logout', {}).then(res=> {
							// 	that.$store.commit("LOGOUT");
							// 	uni.reLaunch({
							// 		url: '/pages/user/index'
							// 	})
							// }).catch(err => {
							// 	that.$util.Tips({
							// 		title: '退出登录失败'
							// 	})
							// })
						}
					}
				})
			},
		}
	}
</script>

<style>
	.container .uni-list image {
		width: 80rpx;
		height: 80rpx;
	}

	.container .uni-list .uni-list-cell {
		margin: 0 30rpx;
		padding: 22rpx 0rpx;
		border-bottom: 1rpx solid #f8f8f8;
	}

	.container .uni-list .uni-list-cell-db {
		text-align: right;
		color: #A8A8A8;
	}

	.uni-navigate-right:after {
		right: 0;
	}

	.pd-30 {
		padding: 30rpx;
	}

	.pic {
		width: 160rpx;
		height: 160rpx;
	}

	.container .pic image {
		width: 100%;
		height: 100%;
	}
</style>